package com.benio.ycfdisplayer.imageloader;

import com.benio.ycfdisplayer.displayer.DisplayListener;
import com.benio.ycfdisplayer.displayer.Executor;
import com.benio.ycfdisplayer.displayer.Options;
import com.benio.ycfdisplayer.displayer.Request;
import com.benio.ycfdisplayer.displayer.Target;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

/**
 * An Executor that loads image into {@link Target}.
 * Created by benio on 2016/11/3.
 */
public class UILExecutor implements Executor {

    public UILExecutor() {
    }

    @Override
    public void execute(Request request) {
        validate(request);
        final String uri = request.getUri();
        final Target target = request.getTarget();
        final Options options = request.getOptions();
        final DisplayListener listener = request.getDisplayListener();

        final DisplayImageOptions displayImageOptions = UILOptionsApplier.applyOptions(options);
        final ImageLoadingListener imageLoadingListener = listener == null ? null : new DisplayListenerAdapter(listener);
        final ImageAware imageAware = UILOptionsApplier.targetToImageAware(target);
        if (imageAware == null) {
            ImageLoader.getInstance().loadImage(uri, null, displayImageOptions, imageLoadingListener, null);
        } else {
            ImageLoader.getInstance().displayImage(uri, imageAware, displayImageOptions, null, imageLoadingListener, null);
        }
    }

    private void validate(Request request) {
        if (request == null) {
            throw new NullPointerException("Request cannot be null");
        }
    }
}
